<template>
    <div class="search" v-show="isSearch">
        <label>
            <input type="text" v-model="search" :placeholder="searchPlaceholder">
            <span class="el-icon-close" ref="empty" v-show="emptyIcon" @click="onEmpty"></span>
            <i class="el-icon-search" @click="onSearch"></i>
        </label>
    </div>


</template>


<script>
export default {
    data() {
        return {
            search: '', //搜索的内容
            emptyIcon: false, //搜索的清空图标
            tempSearch: '', //搜索的临时内容
            isSearch: true, //搜索框
            searchPlaceholder: '请输入你的内容'
        }
    },
    created() {},
    methods: {
        onSearch() {
            let numAddEng = 0
            // 提取英文数字
            for (let i = 0; i <= this.search.length - 1; i++) {
                if (/^[A-Za-z0-9]+$/.test(this.search[i])) {
                    numAddEng++
                }
            }
            // 给清空符号赋值
            if (
                (this.search.length - numAddEng) * 16 + numAddEng * 8 + 20 <=
                360
            ) {
                this.$refs.empty.style.left =
                    (this.search.length - numAddEng) * 16 +
                    numAddEng * 8 +
                    20 +
                    'px'
            } else {
                this.$refs.empty.style.left = 343 + 'px'
            }
            this.emptyIcon = true
            this.tempSearch = this.search
        },
        onEmpty() {
            this.emptyIcon = false
            this.search = ''
        }
    },
    watch: {
        search(newVal) {
            if (newVal != this.tempSearch && this.tempSearch != '') {
                this.emptyIcon = false
                this.tempSearch = ''
            }
        }
    }
}
</script>


<style lang="less">
.search {
    position: absolute;
    left:285px;
    top:18px;
    width: 400px;
    > label {
        display: block;
        border-radius: 23.5px;
        width: 400px;
        height: 45px;
        background-color: #fff;
        > input {
            width: auto;
            border-radius: 23.5px;
            float: left;
            padding: 0 15px;
            height: 45px;
            width: 360px;
        }
        > span {
            position: absolute;
            font-size: 20px;
            color: #999;
            left: 0;
            top: 13px;
        }
        > i {
            font-size: 25px;
            position: absolute;
            color: #999;
            right: 14px;
            top: 10px;
        }
    }
}
</style>

